package com.langyiquan.front.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.langyiquan.config.AliPayResource;
import com.langyiquan.config.WXPayResource;
import com.langyiquan.entity.WxPreOrder;
import com.langyiquan.entity.WxPreOrderResult;
import com.langyiquan.exception.http.OrderException;
import com.langyiquan.pojo.Orders;
import com.langyiquan.pojo.Users;
import com.langyiquan.service.AliPayService;
import com.langyiquan.service.OrderService;
import com.langyiquan.service.UserService;
import com.langyiquan.service.WxPayService;
import com.langyiquan.utils.*;
import com.langyiquan.vo.MiniProgramPaymentVO;
import com.langyiquan.vo.PaymentInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

@Api(value = "支付相关", tags = {"支付的相关接口"})
@RestController
@RequestMapping(value = "payment")
public class PaymentController extends BaseController{

	@Autowired
	public RedisOperator redisOperator;

	@Autowired
	private WXPayResource wxPayResource;

	@Autowired
	private AliPayResource aliPayResource;
	
	@Autowired
	private OrderService orderService;

	@Autowired
	private WxPayService wxPayService;

	@Autowired
	private AliPayService aliPayService;

	@Autowired
	private UserService userService;

	@ApiOperation(value = "小程序创建微信订单",notes = "小程序创建微信订单",httpMethod = "GET")
	@GetMapping(value="/getMiniProgramWXPay")
	public UnifyResponse getMiniProgramWXPay(@RequestParam String orderId, HttpServletRequest request) throws Exception{

		String userId = getPassportUserId(request);

		// 根据订单ID和用户ID查询订单详情
		Orders waitPayOrder = orderService.queryOrder(orderId,userId);
		Users users = userService.queryUserInfo(userId);
		// 商品描述
		String body = "用户ID:[" + userId + "]购买商品,订单ID:为[" + orderId + "]";
		String openid = users.getOpenid();
		// 商户订单号
		String out_trade_no = orderId;
		if (waitPayOrder != null) {

			// 订单总金额，单位为分
			// String total_fee = String.valueOf(waitPayOrder.getPayAmount());
			String total_fee = "1";	// 测试用 1分钱
			// 统一下单
			WxPreOrderResult preOrderResult = wxPayService.placeOrder(body,out_trade_no,total_fee,openid);
			if(!"SUCCESS".equalsIgnoreCase(preOrderResult.getResult_code())) {
				throw new OrderException(7001);
			}else{
				MiniProgramPaymentVO miniProgramPaymentVO = new MiniProgramPaymentVO();
				miniProgramPaymentVO.setAppId(wxPayResource.getAppId());
				miniProgramPaymentVO.setNonceStr(preOrderResult.getNonce_str());
				miniProgramPaymentVO.setSignType("MD5");
				miniProgramPaymentVO.setPackageStr("prepay_id="+preOrderResult.getPrepay_id());
				String timestamp = String.valueOf(new Date().getTime());
				timestamp = timestamp.substring(0,timestamp.length()-3);
				miniProgramPaymentVO.setTimeStamp(timestamp);

				SortedMap<Object, Object> p = new TreeMap<Object, Object>();
				p.put("appId", wxPayResource.getAppId());
				p.put("signType", "MD5");
				p.put("package", "prepay_id="+preOrderResult.getPrepay_id());
				p.put("nonceStr",preOrderResult.getNonce_str());
				p.put("timeStamp",timestamp);
				// 获得签名
				String sign = WxPaySign.createSign("utf-8", p, wxPayResource.getSecrectKey());

				miniProgramPaymentVO.setSign(sign);
				return UnifyResponse.success(miniProgramPaymentVO);
			}


		} else {
			throw new OrderException(6007);
		}
	}
	

	@ApiOperation(value = "PC创建微信订单，获取微信支付二维码",notes = "PC创建微信订单，获取微信支付二维码",httpMethod = "GET")
	@GetMapping(value="/getWXPayQRCode")
	public UnifyResponse getWXPayQRCode(@RequestParam String orderId, HttpServletRequest request) throws Exception{

		String userId = getPassportUserId(request);
		// 根据订单ID和用户ID查询订单详情
    	Orders waitPayOrder = orderService.queryOrder(orderId,userId);

    	// 商品描述
		String body = "付款用户[" + userId + "]";

		// 商户订单号
		String out_trade_no = orderId;
		// 从redis中去获得这笔订单的微信支付二维码，如果订单状态没有支付没有就放入，这样的做法防止用户频繁刷新而调用微信接口
		if (waitPayOrder != null) {
			String qrCodeUrl = redisOperator.get(wxPayResource.getQrcodeKey() + ":" + orderId);

			if (StringUtils.isEmpty(qrCodeUrl)) {
				// 订单总金额，单位为分
				// String total_fee = String.valueOf(waitPayOrder.getPayAmount());
				String total_fee = "1";	// 测试用 1分钱

				// 统一下单
				WxPreOrderResult preOrderResult = wxPayService.placeOrder(body,out_trade_no,total_fee);

				qrCodeUrl = preOrderResult.getCode_url();
			}

			PaymentInfoVO paymentInfoVO = new PaymentInfoVO();
			paymentInfoVO.setAmount(waitPayOrder.getPayAmount());
			paymentInfoVO.setMerchantOrderId(orderId);
			paymentInfoVO.setMerchantUserId(userId);
			paymentInfoVO.setQrCodeUrl(qrCodeUrl);

			redisOperator.set(wxPayResource.getQrcodeKey() + ":" + orderId, qrCodeUrl, wxPayResource.getQrcodeExpire());

			return UnifyResponse.success(paymentInfoVO);
		} else {
			throw new OrderException(6007);
		}
	}


	@ApiOperation(value = "创建支付宝订单，生成支付宝支付链接",notes = "创建支付宝订单，生成支付宝支付链接",httpMethod = "POST")
	@RequestMapping(value="/goAlipay")
	public UnifyResponse goAlipay(String orderId, String userId) throws Exception{

		// 根据订单ID和用户ID查询订单详情
		Orders waitPayOrder = orderService.queryOrder(orderId,userId);

		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(aliPayResource.getGatewayUrl(),
															aliPayResource.getAppId(),
															aliPayResource.getMerchantPrivateKey(),
															"json",
															aliPayResource.getCharset(),
															aliPayResource.getAlipayPublicKey(),
															aliPayResource.getSignType());

		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(aliPayResource.getReturnUrl());
		alipayRequest.setNotifyUrl(aliPayResource.getNotifyUrl());

		String alipayForm = aliPayService.placeOrder(alipayRequest,alipayClient,orderId,userId);

		return UnifyResponse.success(alipayForm);
	}

}
